import Stomp from "stompjs"
import { ref } from 'vue'
let socketOpen = false;
let socketMsgQueue = [];
let subscribeList = [];
let baseURL = 'wss://silkscreen.server.zhhost.top/chat';
let heartbeat = undefined //心跳线程

export default {
	res:ref([]),
	WebSocket: ref(null),
	newitem:ref({}),
	soketOnline: ref(false),
	isnoconnect:ref(false),
    client: null,
    init(_header) {
		this.isnoconnect = false
        if (this.client) {
            return Promise.resolve(this.client);
        }

        return new Promise((resolve, reject) => {
            const ws = {
                send: this.sendMessage,
                onopen: null,
                onmessage: null,
                close: this.closeSocket,
            };

            this.WebSocket = uni.connectSocket({
                url: baseURL,
                header: _header,
            });

            uni.onSocketOpen(function(res) {
                console.log('WebSocket连接已打开！', res);
                socketOpen = true;
                for (let i = 0; i < socketMsgQueue.length; i++) {
                    ws.send(socketMsgQueue[i]);
                }
                socketMsgQueue = [];

                ws.onopen && ws.onopen();
            });

            uni.onSocketMessage(function(res) {
                ws.onmessage && ws.onmessage(res);
            });

            uni.onSocketError(function(res) {
				this.soketOnline.value = false
                console.log('WebSocket 错误！', res);
            });

            uni.onSocketClose(res => {
				this.soketOnline.value = false
                console.log('WebSocket 已关闭！', res);
				socketOpen = false
				//断线重连时，如果没连上，居然也会走到这里
				if(this.client){
					this.client.disconnect();
					this.client = null;
				}
				
				//先取消掉心跳线程
				if(heartbeat) {
					clearInterval(heartbeat)
					heartbeat = undefined
					console.log("心跳线程已清空")
				}
				//取消掉已订阅的
				subscribeList.forEach(t => t.value.unsubscribe())
				if(this.isnoconnect){
					return
				}
                console.log('WebSocket 马上断线重连！');
				setTimeout(() => {
					console.log('WebSocket 开始断线重连！');
					uni.connectSocket({
						url: baseURL,
						header: _header,
					});
				}, 100) //5秒后重连
            });


            const client = this.client = Stomp.over(ws);
			
			// heart-beating是利用window.setInterval()去规律地发送heart-beats或者检查服务端的heart-beats，在小程序中无效，即使增加Stomp.setInterval也是无效
			// client.heartbeat.outgoing = 20000; // 客户端每20000ms发送一次心跳检测
			// client.heartbeat.incoming = 0;     // client不接收serever端的心跳检测
			// Stomp.setInterval = function(interval, f) {
			// 	return setInterval(f, interval);
			// };
			// Stomp.clearInterval = function(id) {
			// 	return clearInterval(id);
			// };
			// console.log(client);
            client.connect(_header, b => {
				this.soketOnline.value = true
                console.log('stomp已连接');
				this.client = client
				heartbeat = setInterval(() => client.send(""), 20*1000)
				//初始化已订阅的，刚启动肯定是空，若有，说明是断线重连的
				subscribeList.forEach(t => {
					t.value = client.subscribe(t.id, d => {
						console.log('d',d);
						let item = { title:d.headers.destination, body:d.body }
						this.newitem.value = item
					});
				})
                resolve(client);
            });
        });
    },
	addSubscribe(title){
		if(!subscribeList.some(t => t.id == title)){
			let subscribe = this.client.subscribe(title, d => {
				// console.log('d',d);
				let item = { title:d.headers.destination, body:d.body }
				this.newitem.value = item
			},err=>{
				console.log(err);
			});
			subscribeList.push({ id:title, value: subscribe })
		}
	},
	delSubscribe(title){
		let tmp = subscribeList.findIndex(t => t.id == title);
		if(tmp > 0){
			subscribeList[tmp].value.unsubscribe()
			subscribeList.splice(tmp, 1)
		}
	},
    disconnect(isnoconnect) {
		this.isnoconnect = isnoconnect
		console.log(this.WebSocket);
		if(this.WebSocket){
			uni.closeSocket();
			this.WebSocket = null
			this.client =null
		}
    },
    sendMessage(message) {
		console.log('message',message);
        if (socketOpen) {
            uni.sendSocketMessage({
                data: message,
            });
        } else {
            socketMsgQueue.push(message);
        }
    },
    closeSocket() {},
};